package com.mentalhealthplatform.global.rbac.controller;

import com.mentalhealthplatform.global.log.manager.ManagerLogAction;
import com.mentalhealthplatform.global.rbac.dto.normal.BaseUserDTO;
import com.mentalhealthplatform.global.rbac.model.User;
import com.mentalhealthplatform.global.debounce.Debounce;
import com.mentalhealthplatform.global.rbac.service.entity.BaseUserService;
import com.mentalhealthplatform.global.rbac.service.relation.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/api/users")
public class BaseUserController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private BaseUserService baseUserService;

    // 根据用户 ID 获取用户及其角色信息
    @GetMapping("/{id}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:READ') or #id == authentication.principal.id")
    public BaseUserDTO getUser(@PathVariable UUID id) {
        // 如果用户不存在，会抛出 UserNotFoundException
        return userRoleService.getUserById(id);
    }

    // 新增用户
    @PostMapping
    @ManagerLogAction(module = "用户管理", operationType = "新增", description = "添加新用户")
    @Debounce
    @PreAuthorize("hasAuthority('USER:CREATE')")
    public ResponseEntity<?> addUser(@RequestBody BaseUserDTO baseUserDTO) {
        User newUser = baseUserService.addUser(baseUserDTO);  // 如果用户已存在，会抛出 UserAlreadyExistsException
        return ResponseEntity.status(201).body(BaseUserDTO.fromUser(newUser));  // 返回 201 Created
    }


    // 获取所有用户及其角色信息
    @GetMapping
    @Debounce
    @PreAuthorize("hasAuthority('USER:READ_ALL')")
    public List<BaseUserDTO> getAllUsers() {
        return userRoleService.getAllUsers();
    }

    // 更新用户信息
    @PutMapping("/{id}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:UPDATE') or #id == authentication.principal.id")
    public ResponseEntity<String> updateUser(@PathVariable UUID id, @RequestBody BaseUserDTO baseUserDTO) {
        // 如果用户名重复或用户不存在，会抛出异常
        baseUserService.updateUser(id, baseUserDTO);
        return ResponseEntity.status(200).body("用户信息更新成功");
    }

    // 切换用户状态
    @PutMapping("/{id}/status")
    @Debounce
    @PreAuthorize("hasAuthority('USER:STATUS_UPDATE')")
    public ResponseEntity<?> updateUserStatus(@PathVariable UUID id, @RequestBody Map<String, Boolean> status) {
        // 如果用户不存在，会抛出异常
        baseUserService.updateUserStatus(id, status.get("status"));
        return ResponseEntity.ok().build();
    }

    // 删除用户
    @DeleteMapping("/{id}")
    @ManagerLogAction(module = "用户管理", operationType = "删除", description = "删除用户")
    @Debounce
    @PreAuthorize("hasAuthority('USER:DELETE') and #id != authentication.principal.id")
    public ResponseEntity<?> deleteUser(@PathVariable UUID id) {
        // 如果用户不存在，会抛出异常
        baseUserService.deleteUser(id);
        return ResponseEntity.ok().build();
    }

    // 批量删除用户
    @PostMapping("/delete")
    @Debounce
    @PreAuthorize("hasAuthority('USER:DELETE_ALL')")
    public ResponseEntity<?> deleteUsers(@RequestBody List<UUID> ids) {
        // 如果某个用户不存在，抛出异常
        ids.forEach(baseUserService::deleteUser);
        return ResponseEntity.ok().build();
    }

    // 授予角色给用户
    @PostMapping("/{userId}/roles/add/{roleId}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:ROLE_ASSIGN')")
    public ResponseEntity<String> addRoleToUser(@PathVariable UUID userId, @PathVariable Long roleId) {
        // 如果用户或角色不存在，会抛出异常
        userRoleService.addRoleToUser(userId, roleId);
        return ResponseEntity.status(200).body("角色授予成功");
    }

    // 撤销用户的角色
    @PostMapping("/{userId}/roles/remove/{roleId}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:ROLE_REMOVE')")
    public ResponseEntity<String> removeRoleFromUser(@PathVariable UUID userId, @PathVariable Long roleId) {
        // 如果用户或角色不存在，会抛出异常
        userRoleService.removeRoleFromUser(userId, roleId);
        return ResponseEntity.status(200).body("角色撤销成功");
    }

}
